/*
 * @Author: chengsl
 * @Date: 2023-02-03 14:41:57
 * @LastEditors: chengsl
 * @LastEditTime: 2023-02-15 09:27:39
 * @Description: 用户、账号信息
 */
import { getUserInfo, loginOutSys } from '@/api/global'
import router from '../../router'
export default {
  namespaced: true,
	state: {
		token: localStorage.token || '',
		userInfo: {}
	},
	mutations: {
		setToken(state, data) {
			state.token = data
			data && (localStorage.token = data)
		},
		setUserInfo(state, data) {
			state.userInfo = data
		}
	},
	actions: {
		// 查用户信息
		setUserInfo({ commit }) {
			return new Promise(async(resolve, reject) => {
				try {
					const res = await getUserInfo()
					if(res.status === 200) {
						commit('setUserInfo', res.data[0])
						resolve()
					}
				} catch (error) {
					reject(error)
				}
			})
		},
		// 退出登录
		loginOut({ commit }) {
			return new Promise(async(resolve, reject) => {
				try {
					const res = await loginOutSys()
					if(res.status === 200) {
						resolve()
					} else {
						reject(res)
					}
				} catch (error) {
					reject(error)
				} finally {
					commit('setToken', '')
					localStorage.removeItem('token')
					router.push('/login')
				}
			})
		}
	}
}
